package thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;

public class MyCompletableFuture {

    public Function<Integer, String> function = num -> {
        System.out.println("开始执行 " + num);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (num > 3) {
            throw new RuntimeException();
        }
        System.out.println("执行完毕 " + num);
        return "执行完毕 " + num;
    };

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        new MyCompletableFuture().methods();
    }

    public void methods() throws InterruptedException {
        ExecutorService customPool = Executors.newFixedThreadPool(5);
        List<CompletableFuture<String>> list = new ArrayList<>();

        for (int i = 1; i < 6; i++) {
            try {
                int finalI = i;
                CompletableFuture<String> feature = CompletableFuture
                        .supplyAsync(() -> finalI)
                        .thenApplyAsync(function, customPool);
//                    .exceptionally(ex -> {
//                        System.err.println("错误: " + ex.getMessage());
//                        return null;
//                    });
                list.add(feature);
            } catch (Exception e) {
                break;
            }
        }

        Thread.sleep(10);
        System.out.println("开始执行...");
        Thread.sleep(10);

        CompletableFuture.allOf(list.toArray(new CompletableFuture[0])).exceptionally(ex -> {
                    System.err.println("部分任务失败: " + ex.getMessage());
                    return null;
                })
                .join(); // 阻塞等待

        for (CompletableFuture<String> stringCompletableFuture : list) {
            boolean success = stringCompletableFuture.isCompletedExceptionally();
            System.out.println(success);
        }
    }

}
